<?php

require_once 'Mail.php' ;

/**
 * Framework_Util_MailWrapper
 *
 * 
 *
 * @author Application Support Group
 * @copyright University of Georgia
 * @package BAMF
 */

class Framework_Util_MailWrapper {



	/**
	 * Framework_Util_MailWrapper::send()
	 *
	 * Send an email message using php's built-in mail function
	 *
	 * @param		array $recipients
	 * @param		array $headers
	 * @param		string $body
	 * @param		string $params Serialized array of SMTP parameters
	 *
	 * @return		mixed
	 *
	 * @package		BAMF
	 * 
	 */

	public static function send( $recipients = array(), $headers = array(), $body = '', $params = SMTP_PARAMS ) {

		$_output = true ;

		$params = unserialize( $params ) ;
		$mailer = Mail::factory( "smtp", $params ) ;

		if (Framework_ErrorHandler::isError( $mailer )) {
			return $mailer ;
		}

		if ( count( $recipients ) == 0 || !isset( $headers['Subject'] ) || !isset( $headers['From'] ) ) {
			$_output = Framework_ErrorHandler::raiseError( "Your mail message must include at least one recipient, a subject, and a from address." ) ;
			return $_output ;
		}

		// The Pear examples duplicate the To address in the header
		//	array. Not sure if that's strictly necessary, but for now we'll
		//	do the same...

		if ( !isset( $headers['To'] )) {
			if ( isset( $recipients['To'] )) {
				$headers['To'] = implode( ", ", $recipients['To'] ) ;
			} else {
				$headers['To'] = implode( ", ", $recipients ) ;
			}
		}


		if( EMAIL_TEST_MODE ) {

			if( !EMAIL_TEST_MODE_RECIPIENT ) { 
				return Framework_ErrorHandler::raiseError( 
						"EMAIL_TEST_MODE is TRUE, however EMAIL_TEST_MODE_RECIPIENT is not set." 
						);
			}

			$body .= "\n\n\nNOTE: Normally, this email would be addressed to:\n" ;

			foreach( $recipients as $nr ) {
				$body .= "\n$nr" ;
			}

			$body .= "\n\nHowever because EMAIL_TEST_MODE is set to true, it has been sent " ;
			$body .= "to the address(es) defined in EMAIL_TEST_MODE_RECIPIENT (".EMAIL_TEST_MODE_RECIPIENT.")." ;
			$body .= "\n\n" ;

			if( strpos( EMAIL_TEST_MODE_RECIPIENT, "," ) > -1 ) {
				$recipients = explode( ",", EMAIL_TEST_MODE_RECIPIENT ) ;
			} else {
				$recipients = array( EMAIL_TEST_MODE_RECIPIENT ) ;
			}

			$headers['To'] = EMAIL_TEST_MODE_RECIPIENT ;
		}

		//
		// PEAR_Mail doesn't automagically send to CC or BCC addresses in the headers
		// and they must be included in the recipients array.
		//
		if( !empty( $headers['CC'] )){ $recipients[] = $headers['CC'] ; }
		if( !empty( $headers['Cc'] )){ $recipients[] = $headers['Cc'] ; }
		if( !empty( $headers['cc'] )){ $recipients[] = $headers['cc'] ; }
		if( !empty( $headers['BCC'] )){ $recipients[] = $headers['BCC'] ; }
		if( !empty( $headers['Bcc'] )){ $recipients[] = $headers['Bcc'] ; }
		if( !empty( $headers['bcc'] )){ $recipients[] = $headers['bcc'] ; }

		$_output = $mailer->send( $recipients, $headers, $body ) ;

		return $_output ;


	}// end send()




}// end class
